<template>
  <view class="container">
    <!-- 操作按钮 -->
    <view class="action-section">
      <view class="input-group">
        <text class="input-label">起始层数：</text>
        <input type="number" v-model="towerStartLevel" class="tower-input"
          placeholder="请输入起始层数(不填默认最高减10层)" :disabled="isRunning" />
      </view>
      <text class="tower-tip">妖塔连续失败10次将自动停止，请重新启动任务</text>
      <button class="action-button" @click="startAutoTask" :disabled="isRunning">
        {{ isRunning ? '任务执行中...' : '开始一键任务' }}
      </button>
    </view>

    <!-- 日志展示区域 -->
    <view class="log-section">
      <view class="log-header">
        <text class="log-title">执行日志</text>
        <button class="clear-button" @click="clearLogs" :disabled="isRunning">清空日志</button>
      </view>
      <scroll-view class="log-content" scroll-y>
        <view v-for="(log, index) in logs" :key="index" class="log-item">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-message">{{ log.message }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  getTempleInfo,
  startPray,
  getBossInfo,
  attackBoss,
  getUnionInfo,
  getBoxInfo,
  openBox,
  getTowerConfig,
  startTowerBattle,
  attackBeast,
  getTowerResult
} from '@/pages/apis/apis'

const isRunning = ref(false)
const unionId = ref(null)
const towerStartLevel = ref('')
const failCount = ref(0)
const userConfig = ref({
  uid: '',
  roleId: ''
})
const logs = ref([
  {
    time: new Date().toLocaleTimeString(),
    message: '老板，恭喜发财，大吉大利！'
  }
])

// 获取用户配置
const getUserConfig = () => {
  try {
    const plunderConfig = uni.getStorageSync('plunder_config') || {}
    userConfig.value = {
      uid: plunderConfig.uid || '',
      roleId: plunderConfig.roleId || ''
    }
    addLog(
      `获取用户配置成功：uid=${userConfig.value.uid}, roleId=${userConfig.value.roleId}`
    )
    return true
  } catch (error) {
    addLog('获取用户配置失败：' + (error.message || '未知错误'))
    return false
  }
}

// 添加日志
const addLog = message => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    message
  })
}

// 清空日志
const clearLogs = () => {
  if (isRunning.value) return
  logs.value = [
    {
      time: new Date().toLocaleTimeString(),
      message: 'Good luck to you!'
    }
  ]
}

// 获取宗门信息
const fetchUnionInfo = async () => {
  try {
    addLog('正在获取宗门ID...')
    const result = await getUnionInfo(userConfig.value.roleId)
    unionId.value = result.id
    addLog('宗门ID获取成功')
    return true
  } catch (error) {
    addLog('获取宗门ID失败：' + (error.message || '未知错误'))
    return false
  }
}

// 处理宝箱任务
const handleBoxTask = async () => {
  try {
    addLog('开始检查宝箱状态...')
    const boxInfo = await getBoxInfo({ roleId: userConfig.value.roleId })

    // 检查三种宝箱
    const boxTypes = [
      { type: 1, name: '矿石宝箱', data: boxInfo.ore },
      { type: 2, name: '灵珠宝箱', data: boxInfo.bead },
      { type: 3, name: '灵脉宝箱', data: boxInfo.veins }
    ]

    for (const box of boxTypes) {
      if (box.data && box.data.logId !== 0) {
        addLog(`发现${box.name}，开始领取...`)
        const result = await openBox({
          logId: box.data.logId,
          roleId: userConfig.value.roleId,
          type: box.type
        })

        if (result.success) {
          addLog(`领取${box.name}成功，获得${box.data.stone || 0}灵石`)
        } else {
          addLog(`领取${box.name}失败：${result.message || '未知错误'}`)
        }
      } else {
        addLog(`没有${box.name}或已被领取，跳过`)
      }
    }

    return true
  } catch (error) {
    addLog('宝箱任务出错：' + (error.message || '未知错误'))
    return false
  }
}

// 处理祈福任务
const handleTempleTask = async () => {
  try {
    // 检查时间是否到达10点
    const now = new Date()
    const currentHour = now.getHours()
    if (currentHour < 10) {
      addLog('祈福时间未到（10:00后开放），跳过祈福任务')
      return true
    }

    addLog('开始检查祈福状态...')
    const templeInfo = await getTempleInfo({
      roleId: userConfig.value.roleId,
      roomId: unionId.value
    })

    // 判断是否已经祈福过（根据buffInfo是否有有效值）
    if (templeInfo.buffInfo && Object.keys(templeInfo.buffInfo).length > 0) {
      addLog('今日已祈福，跳过祈福任务')
      return true
    }

    addLog('今日未祈福，开始祈福...')
    const prayResult = await startPray({
      roleId: userConfig.value.roleId,
      roomId: unionId.value
    })

    if (prayResult.items.length) {
      addLog('祈福成功！')
      return true
    } else {
      addLog('祈福失败：' + (prayResult.message || '未知错误'))
      return false
    }
  } catch (error) {
    addLog('祈福任务出错：' + (error.message || '未知错误'))
    return false
  }
}

// 处理域外天魔任务
const handleBossTask = async () => {
  try {
    // 检查时间是否到达12点
    const now = new Date()
    const currentHour = now.getHours()
    if (currentHour < 12) {
      addLog('域外天魔时间未到（12:00后开放），跳过天魔任务')
      return true
    }

    addLog('开始检查域外天魔状态...')
    const bossInfo = await getBossInfo({ roleId: userConfig.value.roleId })

    // 判断是否已经打过（根据totalHurt是否大于0判断）
    if (bossInfo.remainBattleNum == 0) {
      addLog('今日已打域外天魔，跳过天魔任务')
      return true
    }

    addLog('今日未打域外天魔，开始攻击域外天魔...')
    const battleResult = await attackBoss({ roleId: userConfig.value.roleId })

    if (battleResult.hurt > 0) {
      addLog('攻击域外天魔成功！')
      return true
    } else {
      addLog('攻击域外天魔失败：' + (battleResult.message || '未知错误'))
      return false
    }
  } catch (error) {
    addLog('域外天魔任务出错：' + (error.message || '未知错误'))
    return false
  }
}

// 处理妖塔任务
const handleTowerTask = async () => {
  try {
    addLog('开始检查妖塔状态...')
    const level = parseInt(towerStartLevel.value) || 0

    // 获取妖塔配置
    const config = await getTowerConfig({
      roleId: userConfig.value.roleId,
      roomId: unionId.value,
      level
    })

    addLog(
      `当前妖塔配置：最小层数${config.minLevel}，最大层数${config.maxLevel}`
    )

    // 开始挑战
    let startLevel
    if (towerStartLevel.value) {
      const inputLevel = parseInt(towerStartLevel.value)
      if (inputLevel < config.minLevel) {
        startLevel = config.minLevel
        addLog(
          `输入的层数${inputLevel}小于最小层数${config.minLevel}，将从最小层数开始挑战`
        )
      } else {
        startLevel = inputLevel
      }
    } else if (config.maxLevel - 10 >= config.minLevel) {
      startLevel = config.maxLevel - 10
    } else {
      startLevel = config.minLevel
    }
    addLog(`开始挑战第${startLevel}层妖塔...`)

    let currentLevel = startLevel
    let isContinue = true
    let currentFailCount = 0

    while (isContinue && currentFailCount < 10) {
      // 开始挑战当前层
      const battleResult = await startTowerBattle({
        roleId: userConfig.value.roleId,
        roomId: unionId.value,
        type: currentLevel>config.maxLevel? 1 : 2,
        level: currentLevel
      })

      if (!battleResult.logId) {
        addLog('开始挑战失败：' + (battleResult.message || '未知错误'))
        return false
      }

      let isBattleComplete = false
      let isVictory = false
      let isAttack = false
      let refreshId = battleResult.refreshId // 使用battleResult.logId作为初始refreshId

      // 战斗循环
      while (!isAttack) {
        // 攻击妖兽
        const attackResult = await attackBeast({
          roleId: userConfig.value.roleId,
          roomId: unionId.value,
          beastSn: null
        })

        if (!attackResult) {
          addLog('攻击失败：' + (attackResult.message || '未知错误'))
          return false
        }
        isAttack = true
        addLog('攻击妖兽成功')
      }

      // 战斗循环
      while (!isBattleComplete) {
        // 等待2秒后获取结果
        await new Promise(resolve => setTimeout(resolve, 5000))

        // 获取战斗结果
        const result = await getTowerResult({
          roleId: userConfig.value.roleId,
          roomId: unionId.value,
          logId: battleResult.logId,
          refreshId: refreshId
        })

        // 处理结果
        if (result.items && result.items.length > 0) {
          // 检查是否存在胜利或失败结果
          const victoryItem = result.items.find(
            item => item.type === 'tower-battle-victory'
          )
          const failItem = result.items.find(
            item => item.type === 'tower-battle-fail'
          )

          if (victoryItem) {
            // 战斗胜利
            isBattleComplete = true
            addLog(
              `成功通关第${currentLevel}层！获得${victoryItem.data.beastPill}妖丹`
            )
            isVictory = true
          } else if (failItem) {
            // 战斗失败
            isBattleComplete = true
            addLog(`挑战第${currentLevel}层失败：${failItem.data.tips}`)
            isVictory = false
            refreshId = 0
          } else {
            // 战斗继续
            refreshId = result.refreshId
            addLog('妖塔战斗中，请等待结果...')
          }
        } else {
          // 没有结果，继续查询
          refreshId = result.refreshId
          addLog('等待战斗结果...')
        }
      }

      // 处理战斗结果
      if (isVictory) {
        // 挑战成功，重置失败计数，层数+1
        currentFailCount = 0
        currentLevel++
        addLog(`准备挑战第${currentLevel}层...`)
      } else {
        // 挑战失败，失败计数+1
        currentFailCount++
        addLog(
          `第${currentLevel}层挑战失败，当前失败次数：${currentFailCount}/10`
        )
      }

      // 检查是否继续挑战
      if (currentFailCount >= 10) {
        addLog('连续失败10次，停止挑战更高层')
        isContinue = false
      }
    }

    return true
  } catch (error) {
    addLog('妖塔任务出错：' + (error.message || '未知错误'))
    return false
  }
}

// 开始一键任务
const startAutoTask = async () => {
  if (isRunning.value) return

  isRunning.value = true
  failCount.value = 0
  addLog('开始执行一键任务...')

  try {
    // 执行宝箱任务
    const boxResult = await handleBoxTask()
    if (!boxResult) {
      addLog('宝箱任务失败，停止执行后续任务')
      return
    }

    // 执行祈福任务
    const templeResult = await handleTempleTask()
    if (!templeResult) {
      addLog('祈福任务失败，停止执行后续任务')
      return
    }

    // 执行域外天魔任务
    const bossResult = await handleBossTask()
    if (!bossResult) {
      addLog('域外天魔任务失败，停止执行后续任务')
      return
    }

    // 执行妖塔任务
    const towerResult = await handleTowerTask()
    if (!towerResult) {
      addLog('妖塔任务失败，停止执行后续任务')
      return
    }

    addLog('一键任务执行完成！')
  } catch (error) {
    addLog('任务执行出错：' + (error.message || '未知错误'))
  } finally {
    isRunning.value = false
  }
}

// 页面加载时获取配置和宗门信息
onMounted(async () => {
  if (getUserConfig()) {
    await fetchUnionInfo()
  }
})
</script>

<style>
.container {
  padding: 32rpx;
  min-height: 100vh;
  background: linear-gradient(145deg, #ffffff 0%, #f0f2f5 100%);
  box-sizing: border-box;
}

.action-section {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 8rpx 32rpx rgba(31, 38, 135, 0.15);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.action-section:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 12rpx 48rpx rgba(31, 38, 135, 0.2);
}

.action-button {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background: linear-gradient(135deg, #00c853 0%, #009624 100%);
  color: white;
  border-radius: 48rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  box-shadow: 0 8rpx 24rpx rgba(0, 200, 83, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.action-button::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(rgba(255, 255, 255, 0.2), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.action-button:active {
  transform: scale(0.98) translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 200, 83, 0.2);
}

.action-button:active::after {
  opacity: 1;
}

.action-button:disabled {
  background: linear-gradient(135deg, #e0e0e0 0%, #bdbdbd 100%);
  box-shadow: none;
  transform: none;
}

.log-section {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 32rpx rgba(31, 38, 135, 0.15);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid rgba(0, 200, 83, 0.1);
  position: relative;
}

.log-header::after {
  content: '';
  position: absolute;
  bottom: -2rpx;
  left: 0;
  width: 120rpx;
  height: 2rpx;
  background: #00c853;
}

.log-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  letter-spacing: 1rpx;
}

.log-title::before {
  content: '';
  width: 8rpx;
  height: 36rpx;
  background: linear-gradient(to bottom, #00c853, #009624);
  border-radius: 4rpx;
  margin-right: 16rpx;
}

.clear-button {
  font-size: 28rpx;
  color: #666;
  background: rgba(0, 200, 83, 0.1);
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 32rpx;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.clear-button::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(rgba(255, 255, 255, 0.2), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.clear-button:active {
  background: rgba(0, 200, 83, 0.15);
  transform: scale(0.98);
}

.clear-button:active::after {
  opacity: 1;
}

.clear-button:disabled {
  color: #999;
  background: rgba(0, 0, 0, 0.05);
}

.log-content {
  height: 600rpx;
  background: rgba(248, 249, 250, 0.8);
  border-radius: 20rpx;
  padding: 24rpx;
  position: relative;
  overflow: hidden;
}

.log-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 40rpx;
  background: linear-gradient(rgba(248, 249, 250, 0.8), transparent);
  pointer-events: none;
  z-index: 1;
}

.log-content::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40rpx;
  background: linear-gradient(transparent, rgba(248, 249, 250, 0.8));
  pointer-events: none;
  z-index: 1;
}

.log-item {
  padding: 20rpx;
  margin-bottom: 16rpx;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.log-item:hover {
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transform: translateY(-2rpx);
}

.log-time {
  font-size: 24rpx;
  color: #666;
  margin-right: 16rpx;
  font-family: 'Monaco', monospace;
  background: rgba(0, 200, 83, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.log-message {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  margin-top: 8rpx;
  word-break: break-all;
}

.input-group {
  margin-bottom: 32rpx;
  display: flex;
  align-items: center;
  position: relative;
}

.input-label {
  font-size: 30rpx;
  color: #1a1a1a;
  margin-right: 24rpx;
  font-weight: 500;
  min-width: 140rpx;
}

.tower-input {
  flex: 1;
  height: 88rpx;
  background: rgba(255, 255, 255, 0.9);
  border: 2rpx solid rgba(0, 200, 83, 0.2);
  border-radius: 44rpx;
  padding: 0 40rpx;
  font-size: 30rpx;
  color: #333;
  transition: all 0.3s ease;
  box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.tower-input:focus {
  border-color: #00c853;
  box-shadow: 0 0 0 3rpx rgba(0, 200, 83, 0.1), inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  background: #ffffff;
}

.tower-input:disabled {
  background: rgba(0, 0, 0, 0.05);
  color: #999;
  border-color: transparent;
  box-shadow: none;
}

.tower-tip {
  font-size: 26rpx;
  color: #ff4d4f;
  margin: 24rpx 0 32rpx;
  display: flex;
  align-items: center;
  padding: 20rpx 32rpx;
  background: rgba(255, 77, 79, 0.1);
  border-radius: 16rpx;
  border-left: 8rpx solid #ff4d4f;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-10rpx);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.tower-tip::before {
  content: '!';
  width: 36rpx;
  height: 36rpx;
  line-height: 36rpx;
  text-align: center;
  background: #ff4d4f;
  color: white;
  border-radius: 50%;
  margin-right: 16rpx;
  font-size: 24rpx;
  font-weight: bold;
  box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.3);
}

/* 响应式布局优化 */
@media screen and (min-width: 768px) {
  .container {
    max-width: 1200rpx;
    margin: 0 auto;
    padding: 48rpx;
  }

  .action-section,
  .log-section {
    padding: 48rpx;
    margin-bottom: 48rpx;
  }

  .log-content {
    height: 800rpx;
  }

  .input-group {
    margin-bottom: 40rpx;
  }

  .tower-input {
    max-width: 600rpx;
  }
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .container {
    background: linear-gradient(145deg, #1a1a1a 0%, #2d2d2d 100%);
  }

  .action-section,
  .log-section {
    background: rgba(45, 45, 45, 0.9);
    border-color: rgba(255, 255, 255, 0.1);
  }

  .log-title,
  .input-label {
    color: #ffffff;
  }

  .log-message {
    color: #e0e0e0;
  }

  .tower-input {
    background: rgba(45, 45, 45, 0.9);
    color: #ffffff;
    border-color: rgba(0, 200, 83, 0.3);
  }

  .tower-input:focus {
    background: #2d2d2d;
  }

  .log-content {
    background: rgba(35, 35, 35, 0.8);
  }

  .log-item {
    background: rgba(45, 45, 45, 0.8);
  }

  .log-item:hover {
    background: rgba(45, 45, 45, 0.95);
  }

  .log-time {
    color: #a0a0a0;
    background: rgba(0, 200, 83, 0.15);
  }
}
</style> 